#!/bin/bash

# Flutter 项目重置脚本（Clean + Pub Get）
# 作用：清理项目并重新获取依赖包（完整重置）

echo "🔄 开始重置 Flutter 项目..."
echo "======================================"

# 获取脚本所在目录（项目根目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "📁 当前目录: $(pwd)"
echo "⏰ 开始时间: $(date)"

# 检查是否为 Flutter 项目
if [ ! -f "pubspec.yaml" ]; then
    echo "❌ 错误：当前目录不是 Flutter 项目！"
    echo "请确保脚本位于 Flutter 项目根目录。"
    read -p "按任意键退出..." -n1 -s
    exit 1
fi

echo "✅ 检测到 Flutter 项目"

# 显示项目信息
if command -v grep >/dev/null 2>&1; then
    PROJECT_NAME=$(grep "^name:" pubspec.yaml | cut -d' ' -f2)
    PROJECT_VERSION=$(grep "^version:" pubspec.yaml | cut -d' ' -f2)
    echo "📄 项目名称: $PROJECT_NAME"
    echo "🏷️  项目版本: $PROJECT_VERSION"
fi

echo ""
echo "🔍 即将执行以下操作："
echo "   1. 🧹 清理项目 (flutter clean)"
echo "   2. 📦 获取依赖包 (flutter pub get)"
echo ""

# 步骤 1: Flutter Clean
echo "🧹 步骤 1/2: 正在清理项目..."
echo "----------------------------------------"
flutter clean

if [ $? -eq 0 ]; then
    echo "✅ 项目清理完成"
else
    echo "❌ 项目清理失败"
    echo ""
    echo "按任意键退出..."
    read -n1 -s
    exit 1
fi

echo ""

# 步骤 2: Flutter Pub Get
echo "📦 步骤 2/2: 正在获取依赖包..."
echo "----------------------------------------"
flutter pub get

if [ $? -eq 0 ]; then
    echo "✅ 依赖包获取完成"
else
    echo "❌ 依赖包获取失败"
    echo ""
    echo "按任意键退出..."
    read -n1 -s
    exit 1
fi

echo ""
echo "🎉 Flutter 项目重置完成！"
echo "======================================"
echo "📝 已完成操作："
echo "   ✅ 清理了所有构建缓存"
echo "   ✅ 重新下载了所有依赖包"
echo "   ✅ 更新了 pubspec.lock"
echo "   ✅ 重新生成了 .dart_tool/ 配置"

# 显示依赖包统计信息
if [ -f "pubspec.lock" ]; then
    DEPS_COUNT=$(grep -c "name:" pubspec.lock 2>/dev/null || echo "unknown")
    echo "   📊 总依赖包数量: $DEPS_COUNT"
fi

echo ""
echo "⏰ 完成时间: $(date)"
echo "💡 提示：项目已完全重置，现在可以正常运行 'flutter run'"

# 等待用户按键后关闭
echo ""
echo "按任意键关闭窗口..."
read -n1 -s
